package com.xinnet.mms.allot.service.impl;

import java.net.ConnectException;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.Random;
import java.util.UUID;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.dubbo.remoting.TimeoutException;
import com.sun.xml.internal.ws.policy.privateutil.PolicyUtils.Collections;
import com.xinnet.core.utils.ConfigUtil;
import com.xinnet.mms.allot.dao.CustomAllotDao;
import com.xinnet.mms.allot.service.CustomAllotService;
import com.xinnet.mms.area.dao.AreaDao;
import com.xinnet.mms.area.service.AreaService;
import com.xinnet.mms.cart.service.ShopCartService;
import com.xinnet.mms.common.AppGlobalContainer;
import com.xinnet.mms.company.service.CompanyService;
import com.xinnet.mms.config.service.FlowTurnConfigService;
import com.xinnet.mms.customerConsumeManage.service.CustomerConsumeManageService;
import com.xinnet.mms.customerManage.service.CustomerManageService;
import com.xinnet.mms.customercare.dao.CustomerCareDao;
import com.xinnet.mms.customerstate.service.CustomerStateHistService;
import com.xinnet.mms.dept.service.DeptService;
import com.xinnet.mms.deptarea.service.DeptAreaService;
import com.xinnet.mms.empcustomrelation.service.EmpCustomRelationService;
import com.xinnet.mms.entity.Area;
import com.xinnet.mms.entity.Company;
import com.xinnet.mms.entity.CustomAllotConfig;
import com.xinnet.mms.entity.CustomStateHist;
import com.xinnet.mms.entity.Customer;
import com.xinnet.mms.entity.CustomerCare;
import com.xinnet.mms.entity.Dept;
import com.xinnet.mms.entity.Emp;
import com.xinnet.mms.entity.EmpCustomRelation;
import com.xinnet.mms.entity.Product;
import com.xinnet.mms.entity.PublicConfig;
import com.xinnet.mms.entity.PushHistory;
import com.xinnet.mms.entity.ScanningList;
import com.xinnet.mms.enums.ProductTypeEnum;
import com.xinnet.mms.goods.service.GoodsService;
import com.xinnet.mms.login.service.EmpService;
import com.xinnet.mms.member.service.MemberService;
import com.xinnet.mms.order.dao.OrderDao;
import com.xinnet.mms.order.service.OrderService;
import com.xinnet.mms.product.dao.impl.ProductDaoImpl;
import com.xinnet.mms.product.service.ProductService;
import com.xinnet.mms.utils.CustomerManage;
import com.xinnet.website.analystics.hessian.OutcomingAnalysticsService;
/**
 * 
 * 
 * @author 王湛智[wangzhanzhi@xinnet.com]
 *
 * @version 1.0
 *
 * @since 2014年1月13日
 *
 */
@Service("customAllotService")
public class CustomAllotServiceImpl implements CustomAllotService {
	/**
	 * 客户分配逻辑实现
	 */
	
	/**
	 * 
	 */
	/**客户分配*/
	@Autowired
	private CustomAllotDao customAllotDao;
	/**客户服务*/
	@Autowired
	private CustomerCareDao customerCareDao;
	@Autowired
	private DeptService deptService;
	@Autowired
	private CustomerStateHistService customerStateHistService;
	@Autowired
	private EmpCustomRelationService empCustomRelationService;
	/**xinne库--订单*/
	@Autowired
	private  OrderService orderService;
	/**xinnet库--购物车*/
	@Autowired
	private  ShopCartService shopCartService;
	/**xinet库--商品*/
	@Autowired
	private  GoodsService goodsService;
	/**xinnet库--会员中心*/
	@Autowired
	private  MemberService memberService;
	/**客户产品线流转设置*/
	@Autowired
	private  FlowTurnConfigService flowTurnConfigService;
	/**客户管理*/
	@Autowired
	private CustomerManageService customerManageService;
	/**流量跟踪*/
	@Autowired
	private  OutcomingAnalysticsService outcomingAnalysticsService;
	/**xinne库--订单*/
	@Autowired
	private transient OrderDao orderDao;

	@Autowired
	private AreaService areaService;
	@Autowired
	private DeptAreaService deptAreaService;
	@Autowired
	private CompanyService companyService;
	@Autowired
	private  EmpService empService;
	@Autowired
	private  ProductService productService;
	@Autowired
	private AreaDao areaDao;
	
	@Autowired
	private CustomerConsumeManageService customerConsumeManageService;
	
	private static final SimpleDateFormat sf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	
	static Logger log=LoggerFactory.getLogger(CustomAllotServiceImpl.class);
	
	private boolean deptflag = false;
	
	//单个客户实时分配
	@Override
	@Transactional(propagation=Propagation.REQUIRES_NEW,readOnly=false)
	public void allot(Customer customer,int customerType) throws Exception {
		
		/*//流转至 二次开发老客户/二次开发新客户  只添加推送记录  
		if( customerType == CustomerManage.TWICE_CUSTOMER || 
			customerType == CustomerManage.TWICE_NEW_CUSTOMER ){
			log.info("<流转分配至 二次开发老客户/二次开发新客户>");
			doReDevelopmentCustomer(customer);
			log.info("<--END-->");
			return;
		}*/
		//流转至服务期客户
		if(customerType == CustomerManage.SERVICE_CUSTOMER) {
			log.info("<流转分配至 服务期客户开始>");
			//将客户信息插入客户表
			addNewCustomer(customer);
			doTurnServiceCustomer(customer);
			log.info("<--END-->");
			return;
		}
		//处理流转至公海客户
		if(customerType==CustomerManage.OPEN_SEA_CUSTOMER) {
			log.info("<流转分配至 公海客户>");
			addNewCustomer(customer);
			doOpenSeaCustomer(customer);
			log.info("<--END-->");
			return;
		}/*
		//处理推送至 意向客户
		if(customerType==CustomerManage.INTENTION_CUSTOMER) {
			log.info("<处理推送至 意向客户>");
			doIntentionCustomer(customer);
			log.info("<--END-->");
			return;
		}*/
		//处理拒绝客户
		if(customerType==CustomerManage.ACCEPT_REJECT) {
			log.info("<处理拒绝客户>");
			doRefuseCustomer(customer);
			log.info("<--END-->");
			return;
		}
		//处理回收客户
		if(customerType==CustomerManage.RECYCLING_CUSTOMER) {
			log.info("<处理回收客户>");
			addNewCustomer(customer);
			doRecycleCustomer(customer);
			log.info("<--END-->");
			return;
		}
		//处理客户调配
		if(customerType==CustomerManage.Mix_CUSTOMER) {
			log.info("<处理客户调配>");
			doMixCoustomer(customer);
			log.info("<--END-->");
			return;
		}
		//处理400乐语客户
		if(customerType==CustomerManage.NOT_REGISTER_NEW_CUSTOMER) {
			log.info("<处理400乐语客户>");
			doNotRegisterNewCustomer(customer);
			log.info("<--END-->");
			return;
		}
		//处理保护期客户
//		if(customerType==CustomerManage.PROTCET_CUSTOMER){
//			log.info("<处理保护期客户>");
//			doProtectCustomer(customer);
//			log.info("<--END-->");
//			return;
//		}
		
		//将客户信息插入客户表
		if(addNewCustomer(customer)) return;
		//获得手机号和email一致的报备客户信息
		Customer reported=checkReported(customer);
		//获得手机号和email一致的400乐语客户信息
		Customer tempCustomer=get400Customer(customer);
		//处理报备客户
		if(doReported(customer, reported)) return;
		//处理400乐语客户匹配
		if(do400Customer(customer,tempCustomer)) return;
		//处理新注册服务期客户
		//if(doCustomerService(customer)) return;
		//处理购物车内存在商品的新注册客户
		/*if(doShoppingCartCustomer(customer)) return;*/
		//处理流量跟踪接口返回的产品意向分配
		/*if(doProductLabelCustomer(customer)) return;*/
		//正常新注册客户 调用封装流转数据方法
		if(doDefaultProductCustomer(customer)) return;
	}

	/**
	 * 
	 * 功能描述：正常新注册客户分配
	 *
	 * @param customer
	 * @param dept
	 * @param emp
	 * @param product
	 * @return
	 * @throws SQLException
	 *
	 * @author 王湛智[wangzhanzhi@xinnet.com]
	 *
	 * @since 2014年1月20日
	 *
	 * @update:[变更日期YYYY-MM-DD][更改人姓名][变更描述]
	 */
	public boolean doDefaultProductCustomer(Customer customer) throws Exception {
		PushHistory pushHistory;
		CustomStateHist customerStateHist;
		EmpCustomRelation empCustomRelation;
		//不在设置默认产品
		//Product product=getDefaultProduct();
		Product product = new Product();
		//Product product=getProductByProductId(customer.getProductLabel());
		/*if(product==null) {
			log.info("<没有设置默认产品  无法进行默认产品分配  所有分配方式已经走完  需要设置默认分配产品 否则无法分配客户  该客户未分配:【"+customer.getCusId()+"】>");
			return false;
		}
		log.info("<默认产品是 "+product.getProductName()+"  Code:"+product.getProductCode()+">");*/
		//处理域名专销分配
		/*if(ProductTypeEnum.Domain.getValue().equalsIgnoreCase(product.getProductCode())) {
			log.info("<默认产品进行电销分配>");
			return doDomainCustomer(ProductTypeEnum.Domain.getValue(), customer, CustomerManage.NEW_CUSTOMER);
		}*/
		//修改客户的产品标签
		updateCustomerLabel(customer.getCusId(),product.getProductCode());
		
		customer.setProductName(product.getProductName());
		customer.setProductLabel(product.getProductCode());
		
		//取得部门 
		Dept dept=getDept(customer);
		//如果部门为空则不进行分配
		if(dept==null) {
			log.info("< 未找到部门,公司ID："+customer.getCompanyId()+"---产品ID："+customer.getProductLabel()+" 会员号: "+customer.getCusId()+">");
			return false;
		}
		boolean isReceve = false;
		
		/*if(emp!=null){
			isReceve = true;
		}*/
		//if(emp == null){
			//取得所有符合条件的员工
		Emp emp = null;
		if(customer.getEmpno()!=null && !"".equals(customer.getEmpno())){
			emp = empService.getEmpbyEmpno(customer.getEmpno());
			isReceve = true;
		} else {
			emp=getEmp(dept.getId(),CustomerManage.NEW_CUSTOMER);
				//如果没有员工可以分配则重置该组织排座标记
				if(emp==null) {
					resetAllAllotLabel(dept.getId(),CustomerManage.NEW_CUSTOMER);
					//重新获取符合条件的员工
					emp=getEmp(dept.getId(),CustomerManage.NEW_CUSTOMER);
					//如果该部门下没有员工 则不继续进行操作
					if(emp==null) {
						log.info("<该部门下没有员工  无法进行分配 部门ID:"+dept.getId()+" 部门名称："+dept.getDname()+">");
						return false;
					}
				}
		}
		
	   
		//}
		
		//设置客户类型
		customer.setCustomerType(CustomerManage.NEW_CUSTOMER);
		//封装分配信息
		pushHistory = packagePushHistory(customer, emp, dept, product);
		customerStateHist = customerStateHistService.packageCustomStateHist(emp, customer, dept, product, pushHistory);
		empCustomRelation = empCustomRelationService.packageEmpCustomRelation(emp, customer, product, dept, pushHistory);
		
		if(isReceve){
			pushHistory.setIsReceive(CustomerManage.ACCEPT_YES);
			customerStateHist.setIsReceive(CustomerManage.ACCEPT_YES);
			customerStateHist.setCustomState(CustomerManage.ACCEPT_YES);
			empCustomRelation.setCustomState(CustomerManage.ACCEPT_YES);
			//插入分配历史
			addHistory(pushHistory);
			customerStateHistService.addCustomerStateHist(customerStateHist);
			empCustomRelationService.addEmpCustomRelation(empCustomRelation);
		} else {
			//插入分配历史
			addHistory(pushHistory);
			customerStateHistService.addCustomerStateHist(customerStateHist);
			empCustomRelationService.addEmpCustomRelation(empCustomRelation);
			//将该员工排座标记设为不可排座
			resetAllotLabel(emp.getEmpno(), CustomerManage.NEW_CUSTOMER);
			//将客户ID和当前时间加入timeList
			empCustomRelation.setProductCode(customer.getProductLabel());
			addTimeList(empCustomRelation, customerStateHist,CustomerManage.NEW_CUSTOMER);
		}
		
		log.info("<普通新注册客户分配成功>");
		return true;
	}
	/**
	 * 
	 * 功能描述：处理流浪跟踪接口返回的产品意向分配
	 *
	 * @param customer
	 * @return boolean
	 * @throws Exception
	 *
	 * @author 王湛智[wangzhanzhi@xinnet.com]
	 *
	 * @since 2014年3月24日
	 *
	 * @update:[变更日期YYYY-MM-DD][更改人姓名][变更描述]
	 */
	public boolean doProductLabelCustomer (Customer customer) throws Exception {
		PushHistory pushHistory;
		CustomStateHist customerStateHist;
		EmpCustomRelation empCustomRelation;
		
		String productId="";
		//取得意向标签
		try {
			productId=outcomingAnalysticsService.getModuleIdByCustCode(customer.getCusId());	
		} catch(Exception e) {
			log.error("【allot-hessian-error-timeOut】---<流量跟踪接口未连接>",e);
			return false;
		}
		log.info("----<收到产品标签   该标签是==--——："+productId+">");
		//如果取得的标签为空 则跳出处理 走默认分配
		if(productId==null || productId.equals("notexists") || productId.equals("")) {
			log.info("----<空标签 不进行流量跟踪标签产品分配>");
			return false;
		}
		//处理域名专销分配
		/*if(ProductTypeEnum.Domain.getValue().equalsIgnoreCase(productId)) {
			productId=ProductTypeEnum.Vhost.getValue();
//			log.info("<流量跟踪进行电销分配>");
//			return doDomainCustomer(ProductTypeEnum.Domain.getValue(), customer, CustomerManage.NEW_CUSTOMER);
		}*/
		//修改客户的产品标签
		updateCustomerLabel(customer.getCusId(),productId);
		//用标签拿到产品
		Product product=getProductByProductCode(productId);
		//如果产品为空则跳出处理
		if(product==null) {
			return false;
		}
		//将产品意向set进customer
		customer.setProductName(product.getProductName());
		customer.setProductLabel(product.getProductCode());
		//取得部门 
		Dept dept=getDept(customer);
		//如果部门为空则不进行分配
		if(dept==null) {
			log.info("----<标签已利用 但是该标签对应的部门没有创建==--——："+productId+">");
			return false;
		}
		log.info("----<收到产品标签   该标签对应的部门是==--——："+dept.getDname()+">");
		//取得所有符合分配条件的员工
		Emp emp=getEmp(dept.getId(),CustomerManage.NEW_CUSTOMER);
		//如果没有员工可以分配则重置该组织排座标记
		if(emp==null) {
			resetAllAllotLabel(dept.getId(),CustomerManage.NEW_CUSTOMER);
			//重新获取符合条件的员工
			emp=getEmp(dept.getId(),CustomerManage.NEW_CUSTOMER);
			//如果该部门下没有员工 则不继续进行操作
			if(emp==null) {
				log.info("----<收到产品标签   标签对应的部门没有销售 该会员走默认分配"+customer.getCusId()+">");
				return false;
			}
		}
		//设置客户类型
		customer.setCustomerType(CustomerManage.NEW_CUSTOMER);
		//封装分配信息
		pushHistory = packagePushHistory(customer, emp, dept, product);
		customerStateHist = customerStateHistService.packageCustomStateHist(emp, customer, dept, product, pushHistory);
		empCustomRelation = empCustomRelationService.packageEmpCustomRelation(emp, customer, product, dept, pushHistory);
		
		//插入分配历史
		addHistory(pushHistory);
		customerStateHistService.addCustomerStateHist(customerStateHist);
		empCustomRelationService.addEmpCustomRelation(empCustomRelation);
		
		//将该员工排座标记设为不可排座
		resetAllotLabel(emp.getEmpno(),CustomerManage.NEW_CUSTOMER);
		//将客户ID和当前时间加入timeList
		addTimeList(empCustomRelation, customerStateHist,CustomerManage.NEW_CUSTOMER);
		log.info("<流量跟踪系统-意向标签-新注册客户分配成功>");
		return true;
	}
	/**
	 * 
	 * 功能描述：新注册服务期客户分配
	 *
	 * @param customer
	 * @param dept
	 * @param emp
	 * @param product
	 * @return
	 * @author 王湛智[wangzhanzhi@xinnet.com]
	 * @throws Exception 
	 *
	 * @since 2014年1月20日
	 *
	 * @update:[变更日期YYYY-MM-DD][更改人姓名][变更描述]
	 */
	public boolean doCustomerService(Customer customer) throws Exception {
		PushHistory pushHistory;
		CustomStateHist customerStateHist;
		EmpCustomRelation empCustomRelation;
		
		List<CustomerCare> orderList=orderService.getOrdersByCusId(customer.getCusId());
		if (orderList == null || orderList.isEmpty()) {
			return false;
		}
		//去重复的商品
		List<String> tempProductIiList= new ArrayList<String>();
		List<CustomerCare> tempOrderList = new ArrayList<CustomerCare>();
		
		for(CustomerCare care:orderList) {
			if(care==null || care.getProductId()==null) {
				continue;
			}
			
			if(!tempProductIiList.contains(care.getProductId())){
				tempProductIiList.add(care.getProductId());
				tempOrderList.add(care);
			}
		}
		
		List<Customer> customerList = new ArrayList<Customer>();
		boolean open = true;
		
		for(CustomerCare care:tempOrderList) {
			 		
			if(care.getProductId().substring(0,1).equals("V")) {
				customer.setProductLabel("V");
				List<Customer> cList = orderDao.queryVhostService(customer);
				if(cList==null || cList.size()==0) {
					log.info("会员号:"+customer.getCusId()+"产品未开通");
					open=false;
					break;
				}
				if(cList.get(0)!=null){
					Customer c = cList.get(0);
					customerList.add(c);
				}
			}
			//如果拿到的产品code是CHFW(云主机) 则强制设置为NYZJ(本系统内能识别的云主机CODE)
			else if(care.getProductId().equals(CustomerManage.CHFW)||care.getProductId().equals("NYZJ") ||care.getProductId().equals("XNYY")) {
				if(care.getProductId().equals(CustomerManage.CHFW)){
					customer.setProductLabel("NYZJ");
				} else {
					customer.setProductLabel(care.getProductId());
				}
				
				List<Customer> cList = orderDao.queryIdcServerService(customer);
				if(cList==null ||cList.size()==0) {
					log.info("会员号:"+customer.getCusId()+"产品未开通");
					open=false;
					break;
				}
				if(cList.get(0)!=null){
					Customer c = cList.get(0);
					customerList.add(c);
				}
				if(care.getProductId().equals(CustomerManage.CHFW)){
					customer.setProductLabel("NYZJ");
				} else {
					customer.setProductLabel(care.getProductId());
				}
			}
			//如果拿到的产品code是ZJTG(主机托管) 则强制设置为ZJZY(主机租用)
			else if(care.getProductId().equals(CustomerManage.ZJTG)) {
				customer.setProductLabel(CustomerManage.ZJTG);
				List<Customer> cList = orderDao.queryIdcService(customer);
				if(cList==null ||cList.size()==0) {
					log.info("会员号:"+customer.getCusId()+"产品未开通");
					open=false;
					break;
				}
				if(cList.get(0)!=null){
					Customer c = cList.get(0);
					customerList.add(c);
				}
				customer.setProductLabel(ProductTypeEnum.Hosting.getValue());
			}
			else if(care.getProductId().equals(CustomerManage.MEJZ)) {
				customer.setProductLabel(CustomerManage.MEJZ);
				List<Customer> cList = orderDao.queryJianzhanService(customer);
				if(cList==null ||cList.size()==0) {
					log.info("会员号:"+customer.getCusId()+"产品未开通");
					open=false;
					break;
				}
				Customer c = cList.get(0);
				customerList.add(c);
				customer.setProductLabel(ProductTypeEnum.Jianzhan.getValue());
			}
			else if(care.getProductId().indexOf("EC")!=-1){
				customer.setProductLabel(care.getProductId());
				List<Customer> cList = orderDao.queryChiYunService(customer);
				if(cList==null ||cList.size()==0) {
					log.info("会员号:"+customer.getCusId()+"产品未开通");
					open=false;
					break;
				}
				if(cList.get(0)!=null){
					Customer c = cList.get(0);
					customerList.add(c);
				}
				customer.setProductLabel(ProductTypeEnum.ChiYun.getValue());
			}
			else if(care.getProductId().substring(0, 1).equals(CustomerManage.D)){
				customer.setProductLabel(CustomerManage.D);
				List<Customer> cList = orderDao.queryDomainService(customer);
				if(cList==null ||cList.size()==0) {
					log.info("会员号:"+customer.getCusId()+"产品未开通");
					open=false;
					break;
				}
				if(cList.get(0)!=null){
					Customer c = cList.get(0);
					customerList.add(c);
				}
			}
			else if(care.getProductId().substring(0, 1).equals("M")){
				customer.setProductLabel("M");
				List<Customer> cList = orderDao.queryMailboxService(customer);
				if(cList==null ||cList.size()==0) {
					log.info("会员号:"+customer.getCusId()+"产品未开通");
					open=false;
					break;
				}
				if(cList.get(0)!=null){
					Customer c = cList.get(0);
					customerList.add(c);
				}
			}
			else if(care.getProductId().substring(0, 1).equals("ZJZY")){
				customer.setProductLabel("ZJZY");
				List<Customer> cList = orderDao.queryIdcService(customer);
				if(cList==null ||cList.size()==0) {
					log.info("会员号:"+customer.getCusId()+"产品未开通");
					open=false;
					break;
				}
				if(cList.get(0)!=null){
					Customer c = cList.get(0);
					customerList.add(c);
				}
			}
		}
		
		java.util.Collections.sort(customerList,new Comparator<Customer>(){

			@Override
			public int compare(Customer c1, Customer c2) {
				
				return c2.getDueTime().compareTo(c1.getDueTime());
			}
		});
		if(customerList.size()==0 && open){
			return false;
		}
		if(customerList.size()>0){
			Customer customerEndTime = customerList.get(0);
			customer.setDueTime(customerEndTime.getDueTime());
			//updateCustomerLabel(customer.getCusId(), customer.getProductLabel());
		}
		
		//处理域名专销分配
		/*if(ProductTypeEnum.Domain.getValue().equalsIgnoreCase(customer.getProductLabel())) {
			log.info("<服务期进入电销分配>");
			doDomainCustomer(ProductTypeEnum.Domain.getValue(), customer, CustomerManage.SERVICE_CUSTOMER);
			//修改客户为已购买过商品
			customer.setIsBuy(CustomerManage.BUY_YES);
			customerManageService.modifyCustomerById(customer);
			log.info("<域名专销处理完成>");
			return true;
		}*/
		// 取得对应标签的部门
		Dept dept=getDept(customer);
		if(dept==null) {
			log.info("<ServiceCustomer-Exception--没有负责该产品的部门   无法进行分配>");
			return true;
		}
		Emp emp = empService.getEmpbyEmpno(customer.getEmpId());
		if(emp==null){
			emp = getEmp(dept.getId(),CustomerManage.SERVICE_CUSTOMER);
			// 如果没有员工可以分配则重置该组织排座标记
			if (emp == null) {
				resetAllAllotLabel(dept.getId(),CustomerManage.SERVICE_CUSTOMER);
				// 重新获取符合条件的员工
				emp = getEmp(dept.getId(),CustomerManage.SERVICE_CUSTOMER);
				// 如果该部门下没有员工 则不继续进行操作 将被分配至默认部门
				if (emp == null) {
					log.info("customid:"+customer.getCusId()+"<部门下没有销售 无法进行分配>");
					return true;
				}
			}
		}
		// 取得产品
		Product product = getProductByProductCode(customer.getProductLabel());
		// 客户类型修改为服务期客户
		customer.setCustomerType(CustomerManage.SERVICE_CUSTOMER);
		//封装分配信息
		pushHistory = packagePushHistory(customer, emp, dept, product);
		customerStateHist = customerStateHistService.packageCustomStateHist(emp, customer, dept, product, pushHistory);
		empCustomRelation = empCustomRelationService.packageEmpCustomRelation(emp, customer, product, dept, pushHistory);
		//服务期客户默认都是接收的
		pushHistory.setIsReceive(CustomerManage.ACCEPT_YES);
		customerStateHist.setIsReceive(CustomerManage.ACCEPT_YES);
		customerStateHist.setCustomState(CustomerManage.ACCEPT_YES);
		empCustomRelation.setCustomState(CustomerManage.ACCEPT_YES);
		empCustomRelationService.delEmpCustomRelationByCusId(customer.getCusId());
		customerStateHist.setStartTime(sf.format(new Date()));
		//插入分配历史
		addHistory(pushHistory);
		customerStateHistService.addCustomerStateHist(customerStateHist);
		empCustomRelationService.addEmpCustomRelation(empCustomRelation);
		
		//修改客户为已购买过商品
		customer.setIsBuy(CustomerManage.BUY_YES);
		customer.setCustomerType(CustomerManage.SERVICE_CUSTOMER);
		customerManageService.modifyCustomerById(customer);
		
		// 将该员工排座标记设为不可排座
		resetAllotLabel(emp.getEmpno(),CustomerManage.SERVICE_CUSTOMER);
		/*// 将客户ID和当前时间加入timeList
		addTimeList(empCustomRelation, customerStateHist, CustomerManage.NEW_CUSTOMER);*/
		log.info("<新注册服务期客户分配成功>");
		return true;
	}

	/**
	 * 
	 * 功能描述：报备客户匹配分配
	 *
	 * @param customer
	 * @param reported
	 * @return
	 * @throws SQLException
	 *
	 * @author 王湛智[wangzhanzhi@xinnet.com]
	 *
	 * @since 2014年1月20日
	 *
	 * @update:[变更日期YYYY-MM-DD][更改人姓名][变更描述]
	 */
	public boolean doReported(Customer customer, Customer reported) throws SQLException {
		PushHistory pushHistory;
		CustomStateHist customerStateHist;
		EmpCustomRelation empCustomRelation;
		
		if(reported==null){
			return false;
		}
		
		int count=getCheckReportedCount(customer);
		//IF数量为1 说明有一个新注册客户和报备客户信息匹配成功
		if(count==1) {
			Emp emp=getEmpByEmpno(reported.getReportedEmpId());
			if(emp == null) {
				log.info("<报备该客户的员工可能已经离职，无法进入其报备库>");
				return false;
			}

			//获取员工所属部门
			Dept dept=getDeptByDeptno(emp.getId());
			//如果员工所属部门为空 则不进行分配
			if(dept==null) {
				log.info("<该员工所属部门为空 无法进行分配>");
				return false;
			}
			
			//获取部门负责产品
			Product product=getProductByDeptno(dept.getId());
			if(product==null){
				log.info("<部门负责的产品为空 无法进行分配deptId："+dept.getId()+">");
				return false;
			}
			
			customerConsumeManageService.updateCustomerConsumeCusId(reported,customer);
			delCustomer(reported.getCusId());
			//封装分配信息
			//设置和修改该客户类型为新注册客户
			customer.setCustomerSource("报备");
			customAllotDao.updateCustomerTypeByCusId(customer);
			customAllotDao.updateCustomerSource(customer);
			pushHistory = packagePushHistory(customer, emp, dept, product);
			customerStateHist = customerStateHistService.packageCustomStateHist(emp, customer, dept, product, pushHistory);
			empCustomRelation = empCustomRelationService.packageEmpCustomRelation(emp, customer, product, dept, pushHistory);
			empCustomRelationService.delEmpCustomRelationByCusId(customer.getCusId());
			customerStateHist.setCustomState(CustomerManage.ACCEPT_YES);
			empCustomRelation.setCustomState(CustomerManage.ACCEPT_YES);
			
			//插入分配历史
			addHistory(pushHistory);
			customerStateHistService.addCustomerStateHist(customerStateHist);
			empCustomRelationService.addEmpCustomRelation(empCustomRelation);
			
			log.info("<报备客户分配成功>");
			return true;
		}
		return false;
	}
	/**
	 * 
	 *
	 * 功能描述：处理流转至服务期客户
	 * 
	 * @author 湛智
	 *
	 * @throws 2014年8月20日
	 *
	 */
	public void doTurnServiceCustomer(Customer customer) throws Exception {
		PushHistory pushHistory;
		CustomStateHist customerStateHist;
		EmpCustomRelation empCustomRelation;
		
		if(customer.getCustomerType()!=null && customer.getCustomerType()==CustomerManage.SERVICE_CUSTOMER){
			log.info("<该客户分已经在服务期了，不需要再分配了【"+customer.getCusId()+"】>");
			return;
		}
		if(customer.getCompanyId() == null || customer.getCompanyId().equals("")) {
			log.info("<该客户分公司属性为空 无法进行分配流转【"+customer.getCusId()+"】>");
			return;
		}
		
		Product product=getProductByProductCode(customer.getProductLabel());
		if(product==null) {
			log.info("<找不到产品  无法进行服务期流转 该客户未流转:【"+customer.getCusId()+"】【"+customer.getProductLabel()+"】>");
			return;
		}
		
		/*//如果服务期客户已存在  则不再次进行分配
		if(empCustomRelationService.getEmpCustomRelationByCusIdAndProductCodeAndCustomType(customer.getCusId(), customer.getProductLabel(),CustomerManage.SERVICE_CUSTOMER)!=null) {
			log.info("<已存在该服务期客户 该客户未流转:【"+customer.getCusId()+"】>");
			return;
		}*/
		
		//处理域名专销分配
		/*if(ProductTypeEnum.Domain.getValue().equalsIgnoreCase(product.getProductCode())) {
			log.info("<默认产品进行电销分配>");
			doDomainCustomer(ProductTypeEnum.Domain.getValue(), customer, CustomerManage.SERVICE_CUSTOMER);
		}*/
		
		customer.setProductName(product.getProductName());
		customer.setProductLabel(product.getProductCode());
		
		//取得部门 
		Dept dept=getDept(customer);
		//如果部门为空则不进行分配
		if(dept==null) {
			log.info("< 该部门为空区域ID："+customer.getRegionalId()+"---产品ID："+customer.getProductLabel()+" >");
			return;
		}
		Emp emp = empService.getEmpbyEmpno(customer.getEmpId());
		if(emp == null) {
			//取得所有符合条件的员工
			emp=getEmp(dept.getId(),CustomerManage.SERVICE_CUSTOMER);
			//如果没有员工可以分配则重置该组织排座标记
			if(emp==null) {
				resetAllAllotLabel(dept.getId(),CustomerManage.SERVICE_CUSTOMER);
				//重新获取符合条件的员工
				emp=getEmp(dept.getId(),CustomerManage.SERVICE_CUSTOMER);
				//如果该部门下没有员工 则不继续进行操作
				if(emp==null) {
					log.info("<该部门下没有员工  无法进行分配 部门ID:"+dept.getId()+" 部门名称："+dept.getDname()+">");
					return;
				}
			}
		}
		
		//设置客户类型
		customer.setCustomerType(CustomerManage.SERVICE_CUSTOMER);
		//封装分配信息
		pushHistory = packagePushHistory(customer, emp, dept, product);
		customerStateHist = customerStateHistService.packageCustomStateHist(emp, customer, dept, product, pushHistory);
		empCustomRelation = empCustomRelationService.packageEmpCustomRelation(emp, customer, product, dept, pushHistory);
		//服务期客户默认都是接收的
		customerStateHist.setIsReceive(CustomerManage.ACCEPT_YES);
		customerStateHist.setCustomState(CustomerManage.ACCEPT_YES);
		empCustomRelation.setCustomState(CustomerManage.ACCEPT_YES);
		empCustomRelationService.delEmpCustomRelationByCusId(customer.getCusId());
		customerStateHist.setStartTime(sf.format(new Date()));
		//插入分配历史
		addHistory(pushHistory);
		customerStateHistService.addCustomerStateHist(customerStateHist);
		empCustomRelationService.addEmpCustomRelation(empCustomRelation);
		updateCustomerLabel(customer.getCusId(), customer.getProductLabel());
		updateCustomerTypetoService(customer.getCusId());
		//将该员工排座标记设为不可排座
		resetAllotLabel(emp.getEmpno(),CustomerManage.SERVICE_CUSTOMER);
		//将客户ID和当前时间加入timeList
		/*addTimeList(empCustomRelation, customerStateHist,CustomerManage.SERVICE_CUSTOMER);*/
		log.info("<普通新注册客户分配成功>");
		return;
	}
	/**
	 * 
	 * 功能描述：处理推送至二次开发客户 或 流转客户类型
	 *
	 * @param customer
	 * @throws SQLException
	 *
	 * @author 王湛智[wangzhanzhi@xinnet.com]
	 *
	 * @since 2014年1月20日
	 *
	 * @update:[变更日期YYYY-MM-DD][更改人姓名][变更描述]
	 */
	public void doReDevelopmentCustomer(Customer customer) throws Exception {
		PushHistory pushHistory;
		CustomStateHist customerStateHist;
		EmpCustomRelation empCustomRelation;
		
		//验证customer对象的产品标签
		customer=checkProduct(customer);
		
		//如果区域为空 则默认设置为北京
//		Area area=areaDao.getAreaByAreaId(customer.getRegionalId());
//		if(area==null) {
//			customer.setRegionalId(CustomerManage.BEIJING);
//		}
		//根据客户标签取得部门信息
		customer.setCompanyId(customer.getCompanyId());
		if(customer.getCompanyId() == null || customer.getCompanyId().equals("")) {
			log.info("<该客户分公司属性为空 无法进行分配流转>");
			return;
		}
		
		//找到该客户曾经停留过的产品线以及被推送过的部门
		List<CustomStateHist> cshList = customerStateHistService.getReceiveCustomStateHistByCustomId(customer.getCusId());
		List<String> productList=new ArrayList<String>();
		List<String> deptList=new ArrayList<String>();
		for(CustomStateHist csh:cshList) {
			
			String productCode=csh.getProductCode();
			
			Emp emp=getEmpByEmpno(csh.getEmpId());
			if(emp==null) {
				continue;
			}
			String deptno=emp.getId();
			
			log.debug("<流转中---->查找客户推送过的产品线>");
			//找到客户被推送过的产品
			if(!productList.contains(productCode)) {
				productList.add(productCode);
			}
			
			log.debug("<流转中---->查找客户推送过的部门>");
			//找到客户被推送过的部门
			if(!deptList.contains(deptno)) {
				deptList.add(deptno);
			}
		}
		
		Dept dept=new Dept();

		// 获取产品优先级列表
		List<Product> list = flowTurnConfigService.getAllotPriority();

		// 筛选将要被推送的产品
		for (Product product : list) {
			String productLabel = product.getProductCode();

			log.debug("<流转中---->筛选产品>");
			if (productList.contains(productLabel)) {
				log.info("<产品线推送重复  不进行推送 " + productLabel + ">");
				continue;
			}
			customer.setProductLabel(productLabel);
			dept = getDept(customer);
			if (dept == null || dept.getId().equals("")) {
				log.info("<该分公司没有负责该产品  系统重新选择产品--" + productLabel + "-->");
				continue;
			}

			log.debug("<流转中---->筛选部门>");
			// 筛选将要被推送的部门
			if (deptList.contains(dept.getId())) {
				dept = null;
				log.info("<产品线推送重复  不进行推送 " + productLabel + ">");
				continue;
			}

			break;
		}
		if (dept == null || dept.getId().equals("")) {
			log.info("<该分公司没有负责任何可进行二次开发的产品 " + customer.getCompanyId() + ">");
			return;
		}
		Emp emp=null;
		//处理电销二次开发流转分配
		if(customer.getProductLabel().equals(ProductTypeEnum.Domain.getValue())) {
			emp=empService.getSpecialEmpByProductCode(customer.getProductLabel());
			if(emp==null) {
				deptService.resetAllotLabelByProductCode(ProductTypeEnum.Domain.getValue());
				emp=empService.getSpecialEmpByProductCode(customer.getProductLabel());
				if(emp==null) {
					log.info("<电销销售为空-无法进行分配>");
					return;
				}
			}
		}
		else {
			//根据部门ID取得排座员工信息
			emp=getEmp(dept.getId(),CustomerManage.TWICE_CUSTOMER);
			//如果没有员工可以分配则重置该组织排座标记
			if(emp==null) {
				resetAllAllotLabel(dept.getId(),CustomerManage.TWICE_CUSTOMER);
				//重新获取符合条件的员工
				emp=getEmp(dept.getId(),CustomerManage.TWICE_CUSTOMER);
				//如果该部门下没有员工 则不继续进行操作
				if(emp==null) {
					log.info("<销售为空-无法进行分配>");
					return;
				}
			}
		}
		//修改状态历史表结束时间
		if(customer.getPushHistId()!=null && !customer.getPushHistId().equals("")) {
			customerStateHistService.updateCustomStateHistByPushHistId(customer.getPushHistId());
		}
		//取得该部门负责的产品
		Product product=getProductByProductCode(customer.getProductLabel());
		//设置为系统推送
		customer.setPusherId("system");
		customer.setPushType(CustomerManage.PUSH_TYPE_SYSTEM);
		//封装分配信息
		pushHistory = packagePushHistory(customer, emp, dept, product);
		
		customerStateHist = customerStateHistService.packageCustomStateHist(emp, customer, dept, product, pushHistory);
		empCustomRelation = empCustomRelationService.packageEmpCustomRelation(emp, customer, product, dept, pushHistory);
		
		//插入分配历史
		addHistory(pushHistory);
		customerStateHistService.addCustomerStateHist(customerStateHist);
		empCustomRelationService.addEmpCustomRelation(empCustomRelation);
		
		int customerType = customer.getCustomerType();
		//加入超时扫描列表
		if(customerType == CustomerManage.TWICE_CUSTOMER || customerType == CustomerManage.TWICE_NEW_CUSTOMER) {
			addTimeList(empCustomRelation, customerStateHist, CustomerManage.TWICE_CUSTOMER);
		}
		//将销售设置为不可分配
		resetAllotLabel(emp.getEmpno(),CustomerManage.TWICE_CUSTOMER);
		
		
		log.info("<推送至二次开发客户成功>");
	}
	
	/**
	 * 
	 * 功能描述：处理推送至意向客户
	 *
	 * @param customer
	 * @throws SQLException
	 *
	 * @author 王湛智[wangzhanzhi@xinnet.com]
	 *
	 * @since 2014年1月20日
	 *
	 * @update:[变更日期YYYY-MM-DD][更改人姓名][变更描述]
	 */
	public void doIntentionCustomer(Customer customer) throws Exception {
		PushHistory pushHistory;
		CustomStateHist customerStateHist;
		EmpCustomRelation empCustomRelation;
		
		//記錄下前臺傳送的推送人ID
		String puserId=customer.getPusherId();
		//记录下推送备注
		String remark=customer.getRemark();
		//获得要推送至的部门编号字符串集
		String[] ids=customer.getProductLabel().split(":");
		
		//验证customer对象的产品标签
		customer=checkProduct(customer);
		int doMainLabel=0;
//		//記錄下前臺傳送的推送人ID
//		String puserId=customer.getPusherId();
//		//记录下推送备注
//		String remark=customer.getRemark();
//		//获得要推送至的部门编号字符串集
//		String[] ids=customer.getProductLabel().split(":");
		//根據客戶ID獲取客戶詳細
		customer=getCustomerById(customer.getCusId());
//		String areaId=customer.getRegionalId();
		//如果区域为空 则默认设置为北京
//		Area area=areaDao.getAreaByAreaId(areaId);
//		if(area==null) {
//			areaId=CustomerManage.BEIJING;
//		}
		//获取所有需要推送至的部门
		List<Dept> deptList=customerManageService.getDeptByProductIds(ids,customer.getCompanyId());
		//將記錄的推送人ID放入客戶詳情
		customer.setPusherId(puserId);
		//设置客户类型为意向客户
		customer.setCustomerType(CustomerManage.INTENTION_CUSTOMER);
		//获取推送者部门ID
		String pusherDeptId=getEmpByEmpno(puserId).getId();
		customer.setPusherDeptId(pusherDeptId);
		//将记录的推送备注放入客户详情
		customer.setRemark(remark);
		
		//如果推送产品是域名 (仅域名一项) 则直接进行电销推送
		/*if(ProductTypeEnum.Domain.getValue().equalsIgnoreCase(ids[0]) && ids.length == 1) {
			doDomainCustomer(ProductTypeEnum.Domain.getValue(), customer, CustomerManage.INTENTION_CUSTOMER);
			log.info("推送至意向客户成功");
			return;
		}*/
		
		// 循环处理推送多个意向
		for (Dept dept : deptList) {
			// 取得该部门负责的产品
			List<Product> list=productService.getProductListByDeptno(ids, dept.getId());
			if(list==null || list.isEmpty()) {
				log.info("<部门负责产品为空 无法进行推送>");
				continue;
			}
			//取得部门负责多个产品线进行推送
			for(Product product:list) {
				//记录域名专销分配
				if(ProductTypeEnum.Domain.getValue().equalsIgnoreCase(product.getProductCode())) {
					doMainLabel=1;
					continue;
				}
				// 用推送至部门的编号得到排序的员工
				Emp emp = getEmp(dept.getId(),CustomerManage.INTENTION_CUSTOMER);
				// 如果没有员工可以分配则重置该组织排座标记
				if (emp == null) {
					resetAllAllotLabel(dept.getId(),CustomerManage.INTENTION_CUSTOMER);
					// 重新获取符合条件的员工
					emp = getEmpsByDeptnoIsArtifical(dept.getId());
					// 如果该部门下没有员工 则不继续进行操作
					if (emp == null) {
						return;
					}
				}
				//设置客户类型
				customer.setCustomerType(CustomerManage.INTENTION_CUSTOMER);
				//设置产品Code
				customer.setProductLabel(product.getProductCode());
				// 封装分配信息
				pushHistory = packagePushHistory(customer, emp, dept, product);
				customerStateHist = customerStateHistService.packageCustomStateHist(emp, customer, dept, product,pushHistory);
				empCustomRelation = empCustomRelationService.packageEmpCustomRelation(emp, customer, product, dept,pushHistory);

				// 插入分配历史
				addHistory(pushHistory);
				customerStateHistService.addCustomerStateHist(customerStateHist);
				empCustomRelationService.addEmpCustomRelation(empCustomRelation);

				//将该员工排座标记设为不可排座
				resetAllotLabel(emp.getEmpno(),CustomerManage.INTENTION_CUSTOMER);
				// 将客户ID和当前时间加入timeList
				addTimeList(empCustomRelation, customerStateHist, CustomerManage.INTENTION_CUSTOMER);
			}
		}
		//处理域名专销分配
		if(doMainLabel==1) {
			doDomainCustomer(ProductTypeEnum.Domain.getValue(), customer, CustomerManage.INTENTION_CUSTOMER);
			return;
		}
		log.info("推送至意向客户成功");
	}
	/**
	 * 
	 * 功能描述：处理拒绝客户
	 *
	 * @param customer
	 *
	 * @author 王湛智[wangzhanzhi@xinnet.com]
	 * @throws Exception 
	 * @since 2014年2月26日
	 *
	 * @update:[变更日期YYYY-MM-DD][更改人姓名][变更描述]
	 */
	public void doRefuseCustomer(Customer customer) throws Exception {
		PushHistory pushHistory;
		CustomStateHist customerStateHist;
		EmpCustomRelation empCustomRelation;
		
		//验证customer对象的产品标签
		customer=checkProduct(customer);
		String productLabel = customer.getProductLabel();
		//如果区域为空 则默认设置为北京
//		Area area=areaDao.getAreaByAreaId(customer.getRegionalId());
//		if(area==null) {
//			customer.setRegionalId(CustomerManage.BEIJING);
//		}
		//记录下cusomerType
		int customerType=customer.getCustomerType();
		//记录下推送人ID
		String pusherId=customer.getEmpId();
		//查询出拒绝人详细
		Emp emp=getEmpByEmpno(pusherId);
		//记录下拒绝人部门编号
		String deptno=emp.getId();
		//删除人员客户关系表记录
		empCustomRelationService.delByEcrId(customer.getEcrId());
		//修改被拒绝的客户关系历史客户状态为拒绝
		customerStateHistService.updateCustomStateByCustomIdAndEmpno(customer.getCusId(), emp.getEmpno(), CustomerManage.ACCEPT_REJECT);
		//客户ID查询出客户详细
		customer=getCustomerById(customer.getCusId());
		//设置推送人ID/拒绝人ID
		//customer.setPusherId(pusherId);
		customer.setProductLabel(productLabel);
		//设置客户类型
		customer.setCustomerType(customerType);
		//重新分配至该部门的另一销售
		emp=getEmp(deptno,customerType);
		//如果可分配的员工为空
		if(emp==null) {
			resetAllAllotLabel(deptno,customerType);
			//重新获取符合条件的员工
			emp=getEmp(deptno,customerType);
			//将该员工排座标记设为不可排座
			resetAllotLabel(emp.getEmpno(),customerType);
		}
		//取得推送部门ID
		Dept dept=getDeptByDeptno(deptno);
		//取得产品信息
		Product product=getProductByProductCode(customer.getProductLabel());
		customer.setProductLabel(product.getProductCode());
		//封装分配信息
		pushHistory = packagePushHistory(customer, emp, dept, product);
		customerStateHist = customerStateHistService.packageCustomStateHist(emp, customer, dept, product, pushHistory);
		empCustomRelation = empCustomRelationService.packageEmpCustomRelation(emp, customer, product, dept, pushHistory);
		
		//插入分配历史
		addHistory(pushHistory);
		customerStateHistService.addCustomerStateHist(customerStateHist);
		empCustomRelationService.addEmpCustomRelation(empCustomRelation);
		
		//将该员工排座标记设为不可排座
		resetAllotLabel(emp.getEmpno(),customerType);
		
		//将客户加入timeList
		addTimeList(empCustomRelation, customerStateHist,customerType);
		log.info("<拒绝操作完成>");
	}
	/**
	 * 
	 * 功能描述：处理回收客户
	 *
	 * @param customer
	 * @throws SQLException
	 *
	 * @author 王湛智[wangzhanzhi@xinnet.com]
	 *
	 * @since 2014年3月5日
	 *
	 * @update:[变更日期YYYY-MM-DD][更改人姓名][变更描述]
	 */
	public void doRecycleCustomer(Customer customer) throws SQLException {
		PushHistory pushHistory;
		CustomStateHist customerStateHist;
		EmpCustomRelation empCustomRelation;
		
		//验证customer对象的产品标签
		customer=checkProduct(customer);
		//如果区域为空 则默认设置为北京
//		Area area=areaDao.getAreaByAreaId(customer.getRegionalId());
//		if(area==null) {
//			customer.setRegionalId(CustomerManage.BEIJING);
//		}
		//用销售ID取得销售数据
		Emp emp=getEmpByEmpno(customer.getPusherId());
		//用部门ID取得部门数据
		Dept dept=getDeptByDeptno(customer.getPusherDeptId());
		//用部门ID取得该部门负责产品数据
		Product product=getProductByDeptno(dept.getId());
		//封装分配信息
		pushHistory = packagePushHistory(customer, emp, dept, product);
		customerStateHist = customerStateHistService.packageCustomStateHist(emp, customer, dept, product, pushHistory);
		empCustomRelation = empCustomRelationService.packageEmpCustomRelation(emp, customer, product, dept, pushHistory);
		customerStateHist.setIsReceive(CustomerManage.ACCEPT_YES);
		customerStateHist.setCustomState(CustomerManage.ACCEPT_YES);
		empCustomRelation.setCustomState(CustomerManage.ACCEPT_YES);
		empCustomRelationService.delEmpCustomRelationByCusId(customer.getCusId());
		//插入分配历史
		addHistory(pushHistory);
		customerStateHistService.addCustomerStateHist(customerStateHist);
		
		empCustomRelationService.addEmpCustomRelation(empCustomRelation);
		log.info("<回收客户完成>");
	}
	/**
	 * 
	 * 功能描述：处理流转至公海客户
	 *
	 *
	 * @author 王湛智[wangzhanzhi@xinnet.com]
	 *
	 * @since 2014年3月5日
	 *
	 * @update:[变更日期YYYY-MM-DD][更改人姓名][变更描述]
	 */
	public void doOpenSeaCustomer(Customer customer) throws SQLException {
		PushHistory pushHistory;
		CustomStateHist customerStateHist;
		EmpCustomRelation empCustomRelation;
		
		//如果区域为空 则默认设置为北京
//		Area area=areaDao.getAreaByAreaId(customer.getRegionalId());
//		if(area==null) {
//			customer.setRegionalId(CustomerManage.BEIJING);
//		}
		//流转至公海需要将推送人id设置为system 表示系统推送 这里new一个emp 作为system
		Emp emp=new Emp();
		emp.setEmpno("system");
		customer.setPusherId("system");
		// 封装分配信息
		
		Dept d = null;
		Product p = null;
		/*List<EmpCustomRelation> empCustomRelationList = empCustomRelationService.getEmpCustomRelationByCusId(customer.getCusId());
		if(empCustomRelationList!=null && empCustomRelationList.size()>0){
			String deptId = empCustomRelationList.get(0).getDeptno();
			if(deptId!=null&&"".equals(deptId)){
				d=deptService.getDeptByDeptId(deptId);
			}
			
			String pc = empCustomRelationList.get(0).getProductCode();
			if(pc!=null&&"".equals(pc)){
				List<Product> pList = productService.queryEnableProduct();
				for (Product product : pList) {
					if(product.getProductCode().equals(pc)){
						p=product;
						break;
					}
				}
			}
		}
		
		*/
		String productId = customer.getProductId();
		
		if(productId==null || "".equals(productId)){
			p = this.getDefaultProduct();
		} else {
			List<Product> pList = productService.queryEnableProduct();
			for (Product product : pList) {
				if(product.getId().equals(productId)){
					p=product;
					break;
				}
			}
		}
		
		String deptId=customer.getDeptId();
		if(deptId!=null&&!"".equals(deptId)){
			d=deptService.getDeptByDeptId(deptId);
		}
		if(d==null){
			d=new Dept();
		}
		
		if(p==null){
			p=new Product();
		}
		
		empCustomRelationService.delEmpCustomRelationByCusId(customer.getCusId());
		pushHistory = packagePushHistory(customer, emp, d, p);
		customerStateHist = customerStateHistService.packageCustomStateHist(emp, customer, d, p, pushHistory);
		customerStateHist.setIsReceive(CustomerManage.ACCEPT_YES);
		customerStateHist.setCustomState(CustomerManage.ACCEPT_YES);
		empCustomRelation = empCustomRelationService.packageEmpCustomRelation(emp, customer, p, d, pushHistory);
		empCustomRelation.setCustomState(CustomerManage.ACCEPT_YES);
		
		// 插入分配历史
		addHistory(pushHistory);
		empCustomRelationService.addEmpCustomRelation(empCustomRelation);
		customerStateHistService.addCustomerStateHist(customerStateHist);
		customerManageService.updateCustomer(customer);
		
		
		log.info("<流转至公海客户完成>");
	}
	/**
	 * 
	 * 功能描述：处理400乐语客户
	 *
	 * @param customer
	 * @return
	 * @throws SQLException
	 *
	 * @author 王湛智[wangzhanzhi@xinnet.com]
	 *
	 * @since 2014年4月24日
	 *
	 * @update:[变更日期YYYY-MM-DD][更改人姓名][变更描述]
	 */
	public boolean doNotRegisterNewCustomer(Customer customer) throws Exception {
		PushHistory pushHistory;
		CustomStateHist customerStateHist;
		EmpCustomRelation empCustomRelation;
		//取得产品
		Product product=getProductByProductCode(customer.getProductLabel());
		String productCode=product.getProductCode();
		
		//设置客户类型
		customer.setCustomerType(CustomerManage.NOT_REGISTER_NEW_CUSTOMER);
		//处理域名专销分配
		/*if(ProductTypeEnum.Domain.getValue().equalsIgnoreCase(productCode)) {
			return doDomainCustomer(ProductTypeEnum.Domain.getValue(), customer, CustomerManage.NOT_REGISTER_NEW_CUSTOMER);
		}*/
		//取得区域
		Area area=areaDao.getAreaByAreaId(customer.getRegionalId());
		customer.setAreaName(area.getName());
		customer.setProductName(product.getProductName());
		customer.setProductLabel(product.getProductCode());
		//添加客户
		addNewCustomer(customer);
		//取得部门 
		Dept dept=deptService.getDeptByProductCodeAndAreaId(customer);
		//如果部门为空则不进行分配
		if(dept==null) {
			AppGlobalContainer.is400AllotMap.put("controler", "notAllot");
			return false;
		}
		//取得所有符合条件的员工
		Emp emp=getEmp(dept.getId(),CustomerManage.NOT_REGISTER_NEW_CUSTOMER);
		//如果没有员工可以分配则重置该组织排座标记
		if(emp==null) {
			resetAllAllotLabel(dept.getId(),CustomerManage.NOT_REGISTER_NEW_CUSTOMER);
			//重新获取符合条件的员工
			emp=getEmp(dept.getId(),CustomerManage.NOT_REGISTER_NEW_CUSTOMER);
			//如果该部门下没有员工 则不继续进行操作
			if(emp==null) {
				log.info("<部门下没有销售 无法进行分配>");
				AppGlobalContainer.is400AllotMap.put("controler", "notAllot");
				return false;
			}
		}
		//封装分配信息
		pushHistory = packagePushHistory(customer, emp, dept, product);
		customerStateHist = customerStateHistService.packageCustomStateHist(emp, customer, dept, product, pushHistory);
		empCustomRelation = empCustomRelationService.packageEmpCustomRelation(emp, customer, product, dept, pushHistory);
		
		//插入分配历史
		addHistory(pushHistory);
		customerStateHistService.addCustomerStateHist(customerStateHist);
		empCustomRelationService.addEmpCustomRelation(empCustomRelation);
		
		//将该员工排座标记设为不可排座
		resetAllotLabel(emp.getEmpno(),CustomerManage.NOT_REGISTER_NEW_CUSTOMER);
		
		addTimeList(empCustomRelation, customerStateHist,CustomerManage.NOT_REGISTER_NEW_CUSTOMER);
		log.info("<400乐语客户分配成功>");
		return true;
	}
	/**
	 * 
	 * 功能描述：处理购物车内有商品的新注册客户
	 *
	 * @param customer
	 * @return
	 * @throws SQLException
	 *
	 * @author 王湛智[wangzhanzhi@xinnet.com]
	 * @throws TimeoutException 
	 * @throws ConnectException 
	 *
	 * @since 2014年3月24日
	 *
	 * @update:[变更日期YYYY-MM-DD][更改人姓名][变更描述]
	 */
	public boolean doShoppingCartCustomer(Customer customer) throws Exception {
		PushHistory pushHistory;
		CustomStateHist customerStateHist;
		EmpCustomRelation empCustomRelation;
		
		customer=checkProduct(customer);
		
		//如果客户已存在  则不再次进行分配
		if(empCustomRelationService.getEmpCustomRelationByCusId(customer.getCusId())!=null) {
			log.info("<该会员已被分配 不再进行重复分配  会员ID---【"+customer.getCusId()+"】>");
			return true;
		}
		
		//拿到购物车内产品的标签
		String productId=getShoppingCartByCusId(customer.getCusId());
		if(productId==null || productId.equals("")) {
			log.info("<该会员 购物车内没有商品 不进行购物车处理 会员ID---【"+customer.getCusId()+"】>");
			return false;
		}
		
		log.info("<当前购物车产品标签"+productId+">");
		
		//处理域名专销分配
		/*if(ProductTypeEnum.Domain.getValue().equalsIgnoreCase(productId)) {
			productId=ProductTypeEnum.Vhost.getValue();
//			return doDomainCustomer(ProductTypeEnum.Domain.getValue(), customer, CustomerManage.NEW_CUSTOMER);
		}*/
		//Set产品标签
		customer.setProductLabel(productId);
		//用购物车内的产品标签查出产品
		Product product=getProductByProductCode(productId);
		customer.setProductName(product.getProductName());
		customer.setProductLabel(product.getProductCode());
		//找出该区域负责的部门
		Dept dept=getDept(customer);
		//如果部门为空 表示该区域没有负责该产品的部门 则不进行购物车分配逻辑 跳出处理走默认分配
		if(dept==null) {
			return false;
		}
		//取得部门内将被销售的信息
		Emp emp=getEmp(dept.getId(),CustomerManage.NEW_CUSTOMER);
		//如果没有员工可以分配则重置该组织排座标记
		if(emp==null) {
			resetAllAllotLabel(dept.getId(),CustomerManage.NEW_CUSTOMER);
			//重新获取符合条件的员工
			emp=getEmp(dept.getId(),CustomerManage.NEW_CUSTOMER);
			//如果该部门下没有员工 则不继续进行操作 将被分配至默认部门
			if(emp==null) {
				log.info("<部门下没有员工 无法分配在该部门,部门名称:"+dept.getDname()+">");
				return false;
			}
		}
		//设置客户类型
		customer.setCustomerType(CustomerManage.NEW_CUSTOMER);
		//封装分配信息
		pushHistory = packagePushHistory(customer, emp, dept, product);
		customerStateHist = customerStateHistService.packageCustomStateHist(emp, customer, dept, product, pushHistory);
		empCustomRelation = empCustomRelationService.packageEmpCustomRelation(emp, customer, product, dept, pushHistory);
		
		//插入分配历史
		addHistory(pushHistory);
		customerStateHistService.addCustomerStateHist(customerStateHist);
		empCustomRelationService.addEmpCustomRelation(empCustomRelation);
		
		//将该员工排座标记设为不可排座
		resetAllotLabel(emp.getEmpno(),CustomerManage.NEW_CUSTOMER);
		//加入TimeList扫描接收状态
		addTimeList(empCustomRelation, customerStateHist,CustomerManage.NEW_CUSTOMER);
		log.info("<购物车内意向商品客户分配完成>");
		
		return true;
	}
	//根据客户地域标签和产品标签 得到对应的部门
	@Override
	public Dept getDept(Customer customer) throws SQLException {
		
		List<Dept> deptList = customAllotDao.getDept(customer);
		if(deptList==null||deptList.isEmpty()){
			return null;
		}
//		Random random = new Random();
//		int index = random.nextInt(deptList.size());
		//addtime 2016年10月26日13:32:03 xingzejiang
		int index = 0;
		if(!deptflag){
			index = 0;
			deptflag = !deptflag;
		}else{
			index = 1;
			deptflag = !deptflag;
		}
		
		if(deptList.size()==1){
			index = 0;
		}
		Dept d = deptList.get(index);
		//取得所有符合条件的员工
		Emp emp=getEmp(d.getId(),CustomerManage.NEW_CUSTOMER);
		//如果没有员工可以分配则重置该组织排座标记
		if(emp==null) {
			resetAllAllotLabel(d.getId(),CustomerManage.NEW_CUSTOMER);
			//重新获取符合条件的员工
			emp=getEmp(d.getId(),CustomerManage.NEW_CUSTOMER);
			//如果该部门下没有员工 则不继续进行操作
			if(emp==null) {
				//更换同一个分公司下面的其他部门
				try {
					if(index==0){
						d = deptList.get(index+1);
					} else if(index==1){
						d = deptList.get(index-1);
					}
				} catch (Exception e) {
					log.info("<未查询到部门或部门下没有可以分配的员工，会员号:【"+customer.getCusId()+"】>");
					return null;
				}
			}
		}
		return d;
	}
	
	//用取得的部门标识 得到负责的产品信息
	@Override
	public Product getProductByDeptno(String deptno) throws SQLException {
		return customAllotDao.getProductByDeptno(deptno);
	}

	//将报备信息与新注册客户信息匹配 若手机号和email匹配 两项一致返回真 否则假
	@Override
	public Customer checkReported(Customer customer) throws SQLException {
		return customAllotDao.checkReported(customer);
	}

	//将被分配或被推送员工数据封装进流转表
	@Override
	public PushHistory packagePushHistory(Customer customer, Emp emp,Dept dept, Product product) throws SQLException {
		PushHistory pushHistory=new PushHistory();
		//记录下推送人ID
		//String pusherId=customer.getPusherId();
		//记录下推送备注
		//String remark=customer.getRemark();
		//通过传进来的用户ID查询用户详情
		//customer=getCustomerById(customer.getCusId());
		pushHistory.setId(UUID.randomUUID().toString());
		pushHistory.setPushDate(new java.sql.Date(new java.util.Date().getTime()));
		pushHistory.setPusherId(customer.getPusherId());
		pushHistory.setCusId(customer.getCusId());
		pushHistory.setPushEmpno(emp.getEmpno());
		pushHistory.setPushDeptno(emp.getId());
		pushHistory.setPusherDeptId(customer.getPusherDeptId());
		pushHistory.setPushEname(emp.getEname());
		pushHistory.setRemark(customer.getRemark());
		pushHistory.setPushDname(dept.getDname());
		pushHistory.setIsReceive(CustomerManage.ACCEPT_NO);
		pushHistory.setCustomerType(customer.getCustomerType());
		pushHistory.setIsRecycling(CustomerManage.IS_RECYCLING_NO);
		//如果推送人ID不是系統推送 則推送類型設置為人工推送
		if(customer.getPusherId()==null) {
			pushHistory.setPushType(CustomerManage.PUSH_TYPE_SYSTEM);
		} else {
			if(!customer.getPusherId().equals("system")) {
				pushHistory.setPushType(CustomerManage.PUSH_TYPE_PERSON);
			} else {
				pushHistory.setPushType(CustomerManage.PUSH_TYPE_SYSTEM);
			}
		}
		pushHistory.setPushProductId(product.getId());
		pushHistory.setPushProductName(product.getProductName());
		//如果客户类型为二次开发 则将是否经过二次开发置为真
		if(customer.getCustomerType()==CustomerManage.TWICE_CUSTOMER) {
			pushHistory.setIsRedevel(CustomerManage.TWICE_YES);
		} else {
			pushHistory.setIsRedevel(CustomerManage.TWICE_NO);
		}
		pushHistory.setPushTimeout(1);		
		return pushHistory;
	}
	
	@Override
	public List<Customer> getRebateCustomer(Integer isAllot,
			String timeSet) throws SQLException {
		Customer customer =new Customer();
		customer.setIsAllot(isAllot);
		customer.setTimeStamp(timeSet);
		customer.setTimeStampLimit(Integer.parseInt(ConfigUtil.getString("TIMESTAMPLIMIT")));
		return customAllotDao.getCustomerByAllotState(customer);
	}

	//通过人员标识查询人员信息
	@Override
	public Emp getEmpByEmpno(String empno) throws SQLException {
		return customAllotDao.getEmpByEmpno(empno);
	}

	//通过人员所属部门标识查询部门信息
	@Override
	public Dept getDeptByDeptno(String deptno) throws SQLException {
		return customAllotDao.getDeptByDeptno(deptno);
	}

	//增加流转数据
	@Override
	public void addHistory(PushHistory pushHistory) throws SQLException {
		customAllotDao.addHistory(pushHistory);
	}

	// 获得报备客户信息匹配的客户数量
	@Override
	public int getCheckReportedCount(Customer customer) throws SQLException {
		return customAllotDao.getCheckReportedCount(customer);
	}

	// 将客户信息插入客户表
	@Override
	public boolean addNewCustomer(Customer customer) throws SQLException {
		
		//Product product=getProductByDeptno(dept.getId());
		//Area area=customAllotDao.getAreaByDeptno(dept.getId());
		//customer.setAreaName(area.getName());
		//customer.setRegionalId(area.getAreaID());
		//customer.setProductName(product.getProductName());
		//customer.setProductLabel(product.getId());
		/*customer.setProductLabel(getDefaultProduct().getProductCode());
		Dept dept=getDept(customer);
		Area area=customAllotDao.getAreaByDeptno(dept.getId());
		customer.setAreaName(area.getName());
		customer.setRegionalId(area.getAreaID());*/
		
		Customer customerDB = customAllotDao.getCustomerById(customer.getCusId());
		if(customerDB == null){
			customAllotDao.addNewCustomer(customer); 
			return false;
		} else {
			//解决重复分配的问题
			log.info("该会员已经分配，customId:"+customer.getCusId());
			return true;
		}
		
	}

	//修改客戶類型為意向客戶
	@Override
	public void updateCustomerType(String cusId) throws SQLException {
		customAllotDao.updateCustomerType(cusId);
	}

	//用会员编号查询该会员的订单集
	@Override
	public List<CustomerCare> getOrdersByCusId(String cusId) throws SQLException {
		return customerCareDao.getOrdersByCusId(cusId);
	}
	
	//修改客户类型为服务期客户
	@Override
	public void updateCustomerTypetoService(String cusId) throws SQLException {
		customAllotDao.updateCustomerTypetoService(cusId);
	}

	//将客户服务信息放入客户服务表
	@Override
	public void addCustomerService(CustomerCare customerCare) throws SQLException {
		customAllotDao.addCustomerService(customerCare);
	}

	//通过客户ID获取客户信息
	@Override
	public Customer getCustomerById(String cusId) throws SQLException {
		return customAllotDao.getCustomerById(cusId);
	}
	
	/**
	 * 
	 * 功能描述：将客户加入时间Map 用于扫描接收状态
	 *
	 * @param customer
	 * @param customerType
	 *
	 * @author 王湛智[wangzhanzhi@xinnet.com]
	 * @throws Exception 
	 *
	 * @since 2014年1月20日
	 *
	 * @update:[变更日期YYYY-MM-DD][更改人姓名][变更描述]
	 */
	private void addTimeList(EmpCustomRelation empCustomRelation,CustomStateHist customStateHist,int customerType) throws Exception {
		ScanningList scann=new ScanningList();
		scann.setCusId(empCustomRelation.getCustomId());
		scann.setCustomerType(customerType);
		scann.setEmpno(empCustomRelation.getEmpId());
		scann.setId(UUID.randomUUID().toString());
		scann.setProductLabel(empCustomRelation.getProductCode());
		scann.setPusherId(empCustomRelation.getPusherId());
		scann.setRegionalId(empCustomRelation.getRegionalId());
		scann.setRemark(empCustomRelation.getPushDesc());
		scann.setAddTime(sf.format(new Date()));
		scann.setEcrId(empCustomRelation.getId());
		scann.setCshId(customStateHist.getId());
		scann.setPushHistId(empCustomRelation.getPushHistId());
		customAllotDao.addScanningList(scann);
	}
	
	@Override
	@Transactional(readOnly=false,propagation=Propagation.REQUIRED)
	public void handleScaningList(ScanningList scann) throws Exception{
		Customer customer = getCustomerById(scann.getCusId());
		if(customer==null) {
			customAllotDao.delScanningList(scann.getId());
			log.info("查询扫描客户为空 cusId="+scann.getId());
			return;
		}
		// 取得超时扫描中的信息封装进实体
		EmpCustomRelation empCustomRelation = new EmpCustomRelation();
		CustomStateHist customStateHist = new CustomStateHist();
		PushHistory pushHistory;
		
		Date time = sf.parse(scann.getAddTime());

		// 取得今天是星期几
		Calendar cal = Calendar.getInstance();
		int week = cal.get(Calendar.DAY_OF_WEEK);
		// Calendar获取的是西方星期
		if (week == 1) {
			// 如果返回值为1则说明是星期天
			week = 7;
		} else {
			// 否则将天数减1即得到真是星期数
			week--;
		}
		
		Dept dept = null;
		
		try {
			// 取得分配部门 用以查询客户被分配部门的当天分配规则
			Emp emp = getEmpByEmpno(scann.getEmpno());
			if(emp==null){
				//如果已经离职，则将他未接收的所有客户再次分配
				dept=getDept(customer);
			} else {
				dept = getDeptByDeptno(emp.getId());
			}
			
			
		} catch(Exception e) {
			log.error("<查找部门分配规则失败>",e);
			return;
		}

		if (dept == null) {
			log.info("<部门为空>");
			return;
		}

		// 取得部门当天分配规则
		CustomAllotConfig customerAllotConfig = new CustomAllotConfig();
		customerAllotConfig.setWorkDateNum(week);
		customerAllotConfig.setDeptno(dept.getId());
		customerAllotConfig = customAllotDao.getAllotConfigByDeptno(customerAllotConfig);
		if (customerAllotConfig == null) {
			log.info("<部门分配轮循规则正在审核中 部门ID:"+dept.getId()+">");
			return;
		}
		// 获取从timeList中取得的时间后轮循时间
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(time);
		// 取得部门当天轮循间隔
		int poll = customerAllotConfig.getPollInterval();
		// 如果间隔为0 则表示不分配
		if (poll == 0) {
			// 则直接跳过这个客户 进行下一个客户接收状态扫描
			return;
		}
		// 得到超时未接收的时间
		calendar.add(Calendar.MINUTE, poll);
		Date outDate = calendar.getTime();
		// 获取当前时间 用以和接收超时时间比较
		Date nowTime = new Date();

		// 获取轮循开始时间
		String[] tempStartTime = customerAllotConfig.getStartTime().split(":");
		calendar = Calendar.getInstance();
		calendar.set(Calendar.HOUR_OF_DAY,Integer.parseInt(tempStartTime[0]));
		calendar.set(Calendar.MINUTE, Integer.parseInt(tempStartTime[1]));
		Date startTime = calendar.getTime();
		// 获取轮循结束时间
		String[] tempEndTime = customerAllotConfig.getEndTime().split(":");
		calendar = Calendar.getInstance();
		calendar.set(Calendar.HOUR_OF_DAY, Integer.parseInt(tempEndTime[0]));
		calendar.set(Calendar.MINUTE, Integer.parseInt(tempEndTime[1]));
		Date endTime = calendar.getTime();
		try {
			// 如果当前时间大于轮循开始时间 并且小于轮循结束时间 则进行未接受扫描分配操作
			if (nowTime.after(startTime) && nowTime.before(endTime)) {
				// 取得客户接收状态 查看是否被接受
				boolean customerState = getCustomerState(scann.getCusId(), scann.getEmpno(),scann.getProductLabel());
				// 如果客户分配后超时未接收
				if ((nowTime.after(outDate) || nowTime.equals(outDate)) && customerState == false) {
					
					Customer c = new Customer();
					if(scann.getProductLabel()!=null ||"".equals(scann.getProductLabel())){
						c.setProductLabel(scann.getProductLabel());
					} else {
						c.setProductLabel("NYZJ");
					}
					//Area area = areaService.getAreaByAreaId(areaId);
					String companyIdStr = dept.getCompanyIdStr();
					if(companyIdStr==null||"".equals(companyIdStr)){
						return;
					}
					
					String companyId = companyIdStr.split(",")[0];
					c.setCompanyId(companyId);
					
					Dept d = getDept(c);
					if(d==null){
						log.info("< 未找到部门,公司ID："+c.getCompanyId()+"---产品ID："+c.getProductLabel()+" 会员号: "+scann.getCusId()+">");
						return;
					}
					//取得部门内将被销售的信息
					Emp emp=getEmp(d.getId(),scann.getCustomerType());
					//如果没有员工可以分配则重置该组织排座标记
					if(emp==null) {
						//log.info("<重置超时分配标签>");
						resetAllAllotLabel(d.getId(),scann.getCustomerType());
						//重新获取符合条件的员工
						emp=getEmp(d.getId(),scann.getCustomerType());
						
						//如果该部门下没有员工 则不继续进行操作 将被分配至默认部门
						if(emp==null) {
							log.info("<部门下没有员工 无法分配在该部门,部门名称:"+dept.getDname()+">");
							return;
						}
					}
					
					Product product = getProductByProductCode(scann.getProductLabel());
					if(product==null){
						product = new Product();
					}
					
					//封装推送历史
					pushHistory=packagePushHistory(customer, emp, d, product);
					//如果这条记录已不存在  将其在轮循表中删除
					if(empCustomRelationService.getEmpCustomRelationById(scann.getEcrId())==null) {
						empCustomRelationService.delByEcrId(scann.getEcrId());
						customAllotDao.delScanningList(scann.getId());
						return;
					}
					//修改当前已超时的推送记录
					empCustomRelation.setId(scann.getEcrId());
					empCustomRelation.setEmpId(emp.getEmpno());
					empCustomRelation.setPushHistId(pushHistory.getId());
					empCustomRelation.setDeptno(d.getId());
					customStateHist.setId(scann.getCshId());
					customStateHist.setPushHistId(pushHistory.getId());
					customStateHist.setEmpId(emp.getEmpno());
					empCustomRelationService.updateEmpCustomRelationByEcrId(empCustomRelation);
					customerStateHistService.updateCustomStateHistByCshId(customStateHist);
					
					scann.setEmpno(emp.getEmpno());
					scann.setPushHistId(pushHistory.getId());
					
					addHistory(pushHistory);
					customAllotDao.updateScanningListById(scann);
					//重置分配标签
					//log.info("<" + scann.getCusId()+ "|超时未接收已重新分配|TIME:" + nowTime + ">");
					resetAllotLabel(emp.getEmpno(),scann.getCustomerType());
				} 
				// 如果客户分配后未超时已接受 则不进行重新分配 移除scanninglist中这条客户信息
				if (customerState) {
					customAllotDao.delScanningList(scann.getId());
				}
				
			}
		} catch (Exception e) {
			log.error("<allot-scanning-error-nullpoint>"+e.getMessage(), e);
		}
	
	}
	
	
	

	//通过用户ID查询客户被分配状态
	@Override
	public boolean getCustomerState(String cusId,String empno,String productCode) throws SQLException {
		//如果客户已分配返回 真 否则 假
		List<EmpCustomRelation> empCustomRelationList = empCustomRelationService.getEmpCustomRelationByCusId(cusId);
		if(empCustomRelationList==null || empCustomRelationList.size()==0){
			return false;
		}
		EmpCustomRelation empCustomRelation = empCustomRelationList.get(0);
		if(empCustomRelation.getCustomState()==1) {
			return true;
		}
		return false;
	}

	/**处理调配客户*/
	@Override
	public void doMixCoustomer(Customer customer) throws Exception {
		PushHistory pushHistory;
		CustomStateHist customerStateHist;
		EmpCustomRelation empCustomRelation;
		
		Emp emp=new Emp();
		Dept dept=new Dept();
		Product product=new Product();
		product.setProductCode(customer.getProductCode());
		//取得调配到销售ID
		String mixEmpno=customer.getMixEmpno();
		//取得调配到部门ID
		String mixDeptno=customer.getMixDeptno();
		
		dept=getDeptByDeptno(mixDeptno);
		//String areaId = dept.getAreaParentId();
		String deptId = dept.getId();
		List<Area> areaList = deptAreaService.getAreaByDeptId(deptId);
		if(areaList!=null && !areaList.isEmpty()){
			customer.setAreaName(areaList.get(0).getName());
			customer.setRegionalId(areaList.get(0).getAreaID());
		}
		//Area area = areaService.getAreaByAreaId(areaId);
		String companyIdStr = dept.getCompanyIdStr();
		if(companyIdStr!=null && !"".equals(companyIdStr)){
			String companyId = companyIdStr.split(",")[0];
			customer.setCompanyId(companyId);
			Company company = companyService.getCompanyById(companyId);
			if(company!=null){
				customer.setCompanyAbb(company.getCompanyAbb());
			}
		}
		
		//如果调配到销售不为空
		if(mixEmpno!=null && !mixEmpno.equals("")) {
			emp=getEmpByEmpno(mixEmpno);
			
			//product=getProductByDeptno(mixDeptno);
			log.info("<直接调配操作完成>");
		}
		else {
			//取得产品信息
			//product=getProductByDeptno(mixDeptno);
			//处理域名专销分配
			/*if(ProductTypeEnum.Domain.getValue().equalsIgnoreCase(product.getProductCode())) {
				doDomainCustomer(ProductTypeEnum.Domain.getValue(), customer, customer.getCustomType());
				return;
			}*/
			//取得推送部门ID
			
			
			//取得所有符合条件的员工
			emp=getEmp(dept.getId(),customer.getCustomerType());
			//如果没有员工可以分配则重置该组织排座标记
			if(emp==null) {
				resetAllAllotLabel(dept.getId(),customer.getCustomerType());
				//重新获取符合条件的员工
				emp=getEmp(dept.getId(),customer.getCustomerType());
				//如果该部门下没有员工 则不继续进行操作
				if(emp==null) {
					log.info("<部门下没有员工 无法分配在该部门,部门名称:"+dept.getDname()+">");
					return;
				}
				log.info("<指定部门调配操作完成>");
			}
		}
		empCustomRelationService.delEmpCustomRelationByCusId(customer.getCusId());
		//封装分配信息  如果是公海客户，更新状态为回收客户
		if(customer.getCustomerType().equals(CustomerManage.OPEN_SEA_CUSTOMER)){
			customer.setCustomerType(CustomerManage.RECYCLING_CUSTOMER);
			customAllotDao.updateCustomerTypeByCusId(customer);
		}
		
		customAllotDao.updateCustomerAreaByCusId(customer);
		pushHistory = packagePushHistory(customer, emp, dept, product);
		customerStateHist = customerStateHistService.packageCustomStateHist(emp, customer, dept, product, pushHistory);
		empCustomRelation = empCustomRelationService.packageEmpCustomRelation(emp, customer, product, dept, pushHistory);
		empCustomRelation.setCustomState(CustomerManage.ACCEPT_YES);
		customerStateHist.setCustomState(CustomerManage.ACCEPT_YES);
		
		//插入分配历史
		addHistory(pushHistory);
		customerStateHistService.addCustomerStateHist(customerStateHist);
		empCustomRelationService.addEmpCustomRelation(empCustomRelation);
		customerConsumeManageService.updateCustomerConsumeEmp(customer,emp);
		Integer customerTypeInt = null;
		if(customer.getCustomerType()==8){
			customerTypeInt = CustomerManage.OPEN_SEA_CUSTOMER;
		} else {
			customerTypeInt = customer.getCustomerType();
		}
		//将该员工排座标记设为不可排座
		resetAllotLabel(emp.getEmpno(),customerTypeInt);
		return;
	}

	/**用会员ID查看该会员购物车内的商品 返回优先级最高的产品*/
	@Override
	public String getShoppingCartByCusId(String cusId) throws SQLException {
		
		String[] productIds = new String[500];
		productIds = goodsService.getProductClassByCusId(cusId);
		//如果产品ID为空则不进行排序
		if(productIds==null || productIds[0]==null || productIds[0].equals("")) {
			return null;
		}
		//返回优先级最高的产品
		return getAllotProductMaxPriority(productIds);
	}

	/**用产品标签查出产品*/
	@Override
	public Product getProductByProductId(String productId) throws SQLException {
		return customAllotDao.getProductByProductId(productId);
	}

	/**获取默认分配的产品线*/
	@Override
	public Product getDefaultProduct() throws SQLException {
		PublicConfig config=flowTurnConfigService.getDefaultProduct();
		return getProductByProductId(config.getConfigValue());
	}

	/**用会员ID获取流量跟踪接口返回的该会员的产品意向*/
	@Override
	public String getProductLabelFromDubbo(String cusId) {
		try {
			//return userRegProService.getUserRegPro(cusId);
			return null;
		} catch(Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	/**根据ID删除客户*/
	@Override
	public void delCustomer(String cusId) throws SQLException {
		customAllotDao.delCustomer(cusId);
	}

	/**给出多个产品ID 得到优先级最高的产品*/
	@Override
	public String getAllotProductMaxPriority(String[] productIds) throws SQLException {
		//如果产品为空则不进行排序
		if(productIds.length == 0) {
			return null;
		}
		List<Product> list=new ArrayList<Product>();
		//取得每个产品的优先级排序
		for(int i=0;i<productIds.length;i++) {
			//如果产品id为空 则不进行排序
			Product product=getProductByProductCode(productIds[i]);
			if(product==null) {
				continue;
			}
			list.add(product);
		}
		//如果产品为空 则不进行排序
		if(list.isEmpty()) {
			return null;
		}
		//找出最大分配优先级排序的产品id 即分配优先级排序为最小
		int priority=list.get(0).getAllotPriority();
		String pid=list.get(0).getProductCode();
		int i=0;
		for(Product product:list) {
			int nowPriority=product.getAllotPriority();
			if(priority>nowPriority) {
				priority=nowPriority;
				pid=list.get(i).getProductCode();
			}
			i++;
		}
		return pid;
	}

	/**取得父节点部门*/
	@Override
	public Dept getParentDept(String deptno) throws SQLException {
		return customAllotDao.getParentDept(deptno);
	}

	/**修改人员客户关系*/
	@Override
	public void updateEmpAndCustomer(Customer customer) throws SQLException {
		customAllotDao.updateEmpAndCustomer(customer);
	}
	
	/**修改客户分配状态*/
	@Override
	public void updateCustomerIsAllot(Customer customer) throws SQLException {
		customAllotDao.updateCustomerIsAllot(customer);
	}
	/**根据商品code获取商品类型*/
	@Override
	public String getGoodsTypeByGoodsCode(String goodsCode) {
		return goodsCode;
	}

	/**用客户ID和销售ID找出超时的推送记录并删除*/
	@Override
	public void delPushHistoryByCusIdAndEmpno(Customer customer, Emp emp) throws SQLException {
		customer.setEmpno(emp.getEmpno());
		customAllotDao.delPushHistoryByCusIdAndEmpno(customer);
	}

	/**
	 * 修改客户产品标签
	 */
	@Override
	public void updateCustomerLabel(String cusId,String productId) throws SQLException {
		customAllotDao.updateCustomerLabel(cusId, productId);
	}

	/**
	 * 通过productCode获取product
	 */
	@Override
	public Product getProductByProductCode(String prodcutCode) throws SQLException {
		return customAllotDao.getProductByProductCode(prodcutCode);
	}

	/**
	 * 查询支持人工推送的emp
	 */
	@Override
	public Emp getEmpsByDeptnoIsArtifical(String deptno) throws SQLException {
		return customAllotDao.getEmpsByDeptnoIsArtifical(deptno);
	}

	/**
	 * 处理400乐语客户匹配
	 */
	@Override
	public boolean do400Customer(Customer customer, Customer tempCustomer) throws Exception {
		//如果400客户为空则不处理
		if(tempCustomer==null) {
			return false;
		}
		customerConsumeManageService.updateCustomerConsumeCusId(tempCustomer,customer);
		//将400客户的临时信息替换为注册的新客户信息
		delCustomer(tempCustomer.getCusId());
		customer.setCustomerType(CustomerManage.NEW_CUSTOMER);
		customer.setCustomerSource("400");
		customer.setCustomId(tempCustomer.getCusId());
		customAllotDao.updateCustomerSource(customer);
		empCustomRelationService.updateEmpCustomRelationCusId(customer);
		return true;
	}

	/**
	 * 根据手机邮箱获取400乐语客户
	 */
	@Override
	public Customer get400Customer(Customer customer) throws SQLException {
		return customAllotDao.get400Customer(customer);
	}

	/**
	 * 修改客户信息
	 */
	@Override
	public void updateCustomerInfo(Customer customer) throws SQLException {
		customAllotDao.updateCustomerInfo(customer);
	}

	/**
	 * 根据cusId和productLabel查询客户表记录数
	 */
	@Override
	public Integer getServiceCustomerCountByCusIdAndProductLabel (Customer customer) throws SQLException {
		return customAllotDao.getServiceCustomerCountByCusIdAndProductLabel(customer);
	}

	/**
	 * 处理电销客户分配
	 */
	@Override
	public boolean doDomainCustomer(String productCode,Customer customer,Integer customerType) throws Exception {
		PushHistory pushHistory;
		CustomStateHist customerStateHist;
		EmpCustomRelation empCustomRelation;
		log.info("<电销分配开始>");
		//设置客户类型
		customer.setCustomerType(customerType);
		
		Emp emp=empService.getSpecialEmpByProductCode(productCode);
		
		//修改客户的产品标签
		customer.setProductLabel(productCode);
		updateCustomerLabel(customer.getCusId(),productCode);
		
		if(emp==null) {
			log.info("<当前可分配销售为空 重置所有标记>");
			deptService.resetAllotLabelByProductCode(productCode);
			emp=empService.getSpecialEmpByProductCode(productCode);
			if(emp==null) {
				log.info("<电销销售为空-无法进行分配>");
				return false;
			}
		}
		log.info("<当前选择分配的销售---"+emp.getEname()+"Code:"+emp.getEmpno()+">");
		Dept dept = getDeptByDeptno(emp.getId());
		if(dept==null) {
			log.info("<电销部门为空-无法进行分配>");
			return false;
		}
		Product product = getProductByProductCode(productCode);
		if(product==null) {
			log.info("<电销产品为空-无法进行分配>");
			return false;
		}
		//封装分配信息
		pushHistory = packagePushHistory(customer, emp, dept, product);
		customerStateHist = customerStateHistService.packageCustomStateHist(emp, customer, dept, product, pushHistory);
		empCustomRelation = empCustomRelationService.packageEmpCustomRelation(emp, customer, product, dept, pushHistory);
		
		//服务期客户默认都是接收的
		empCustomRelation.setCustomState(CustomerManage.ACCEPT_YES);
		customerStateHist.setCustomState(CustomerManage.ACCEPT_YES);
		customerStateHist.setStartTime(sf.format(new Date()));
		//插入分配历史
		addHistory(pushHistory);
		empCustomRelationService.delEmpCustomRelationByCusId(customer.getCusId());
		customerStateHistService.addCustomerStateHist(customerStateHist);
		empCustomRelationService.addEmpCustomRelation(empCustomRelation);
		log.info("<电销分配完成 对销售进行标记"+emp.getEmpno()+" : "+emp.getEname()+">");
		resetSpecialEmpAllotLabel(emp.getEmpno());
		log.info("<电销分配成功>");
		return true;
	}

	/**
	 * 获取相同手机号/邮箱的客户
	 */
	@Override
	public Customer getCheckAlikeCustomer(Customer customer) throws Exception {
		List<Customer> list=customAllotDao.getCheckAlikeCustomer(customer);
		if(list==null || list.isEmpty()) {
			return null;
		}
		return list.get(0);
	}
	
	/**
	 * 获取相同手机号/邮箱的客户
	 */
	@Override
	public Customer getCheckCustomerByPhone(Customer customer) throws Exception {
		List<Customer> list=customAllotDao.getCheckCustomerByPhone(customer);
		if(list==null || list.isEmpty()) {
			return null;
		}
		return list.get(0);
	}
	
	
	
	/**
	 * 验证Customer的产品标签
	 * @throws SQLException 
	 */
	@Override
	public Customer checkProduct(Customer customer) throws SQLException {
		String productCode=customer.getProductLabel();
		if(productCode!=null && !productCode.equals("")) {
			//如果拿到的产品code是CHFW(云主机) 则强制设置为NYZJ(本系统内能识别的云主机CODE)
			if(productCode.equals(CustomerManage.CHFW)) {
				customer.setProductLabel(ProductTypeEnum.Cloud.getValue());
			}
			//如果拿到的产品code是ZJTG(主机托管) 则强制设置为ZJZY(主机租用)
			else if(productCode.equals(CustomerManage.ZJTG)) {
				customer.setProductLabel(ProductTypeEnum.Hosting.getValue());
			}
			else if(productCode.equals(CustomerManage.MEJZ)) {
				customer.setProductLabel(ProductTypeEnum.Jianzhan.getValue());
			}
		} else {
			customer.setProductLabel(getDefaultProduct().getProductCode());
		}
		return customer;
	}

	/**
	 * 修改扫描表记录
	 */
	@Override
	public void updateScanningListById(ScanningList scann) throws SQLException {
		customAllotDao.updateScanningListById(scann);
	}
	
	public List<ScanningList> getAllScanningList() throws SQLException{
		return customAllotDao.getAllScanningList();
	}
	
	@Override
	public int getScanningCountByEmpno(String empno) throws SQLException {
		// TODO Auto-generated method stub
		return customAllotDao.countByEmpno(empno);
	}

	/**
	 * 
	 *
	 * 功能描述：获取要清洗的数据
	 * 
	 * @author 湛智
	 *
	 * @throws 2014年8月13日
	 *
	 */
	public List<Customer> getFlushDataCustomer() throws SQLException{
		return this.customAllotDao.getFlushDataCustomer();
	}

	/**
	 * 重置部门所有销售超时未接收标签
	 */
	@Override
	public void resetScannAllAllotLabel(String deptno, Integer customerType) throws SQLException {
		
		if(customerType==CustomerManage.NEW_CUSTOMER) {
			customAllotDao.resetAllScannNewEmp(deptno);
		}
		
		else if(customerType==CustomerManage.INTENTION_CUSTOMER) {
			customAllotDao.resetAllScannIntetionEmp(deptno);
		}
		
		else if(customerType==CustomerManage.SERVICE_CUSTOMER) {
			customAllotDao.resetAllScannServiceEmp(deptno);
		}
		
		else if(customerType==CustomerManage.NOT_REGISTER_NEW_CUSTOMER) {
			customAllotDao.resetAllScannNotRegEmp(deptno);
		}
		
		else if(customerType==CustomerManage.TWICE_CUSTOMER) {
			customAllotDao.resetAllScannTwiceEmp(deptno);
		}
	}

	/**
	 * 根据类型获取超时未接收销售
	 */
	@Override
	public Emp getScannEmp(String deptno, Integer customerType) throws SQLException {
		
		if(customerType==CustomerManage.NEW_CUSTOMER) {
			return customAllotDao.getScannNewEmp(deptno);
		}
		
		else if(customerType==CustomerManage.INTENTION_CUSTOMER) {
			return customAllotDao.getScannIntetionEmp(deptno);
		}
		
		else if(customerType==CustomerManage.SERVICE_CUSTOMER) {
			return customAllotDao.getScannServiceEmp(deptno);
		}
		
		else if(customerType==CustomerManage.NOT_REGISTER_NEW_CUSTOMER) {
			return customAllotDao.getScannNotRegEmp(deptno);
		}
		
		else if(customerType==CustomerManage.TWICE_CUSTOMER) {
			return customAllotDao.getScannTwiceEmp(deptno);
		}
		else {
			return null;
		}
	}

	/**
	 * 根据类型标记销售超时未接收重新分配新标签
	 */
	@Override
	public void resetScannAllotLabel(String empno, Integer customerType) throws SQLException {
		
		if(customerType==CustomerManage.NEW_CUSTOMER) {
			customAllotDao.resetScannNewEmp(empno);
		}
		
		else if(customerType==CustomerManage.INTENTION_CUSTOMER) {
			customAllotDao.resetScannIntetionEmp(empno);
		}
		
		else if(customerType==CustomerManage.SERVICE_CUSTOMER) {
			customAllotDao.resetScannServiceEmp(empno);
		}
		
		else if(customerType==CustomerManage.NOT_REGISTER_NEW_CUSTOMER) {
			customAllotDao.resetScannNotRegEmp(empno);
		}
		
		else if(customerType==CustomerManage.TWICE_CUSTOMER) {
			customAllotDao.resetScannTwiceEmp(empno);
		}
	}

	/**
	 * 重置部门所有销售接收客户标签
	 */
	@Override
	public void resetAllAllotLabel(String deptno, Integer customerType) throws SQLException {
		if(customerType==CustomerManage.NEW_CUSTOMER) {
			customAllotDao.resetAllNewAllotLabel(deptno);
		}
		
		else if(customerType==CustomerManage.INTENTION_CUSTOMER) {
			customAllotDao.resetAllIntetionAllotLabel(deptno);
		}
		
		else if(customerType==CustomerManage.SERVICE_CUSTOMER) {
			customAllotDao.resetAllServiceAllotLabel(deptno);
		}
		
		else if(customerType==CustomerManage.NOT_REGISTER_NEW_CUSTOMER) {
			customAllotDao.resetAllNotRegAllotLabel(deptno);
		}
		
		else if(customerType==CustomerManage.OPEN_SEA_CUSTOMER) {
			customAllotDao.resetAllTwiceAllotLabel(deptno);
		}
	}

	/**
	 * 根绝类型获取可接收客户的销售
	 */
	@Override
	public Emp getEmp(String deptno, Integer customerType) throws SQLException {
		
		if(customerType==CustomerManage.NEW_CUSTOMER) {
			return customAllotDao.getNewEmp(deptno);
		}
		
		else if(customerType==CustomerManage.SERVICE_CUSTOMER) {
			return customAllotDao.getServiceEmp(deptno);
		}
		
		else if(customerType==CustomerManage.NOT_REGISTER_NEW_CUSTOMER) {
			return customAllotDao.getNotRegEmp(deptno);
		}
		
		else if(customerType==CustomerManage.OPEN_SEA_CUSTOMER) {
			return customAllotDao.getTwiceEmp(deptno);
		}
		else {
			return null;
		}
	}

	/**
	 * 根绝类型标记销售接收客户标签
	 */
	@Override
	public void resetAllotLabel(String empno, Integer customerType) throws SQLException {
		
		if(customerType==CustomerManage.NEW_CUSTOMER) {
			customAllotDao.resetNewAllotLabel(empno);
		}
		
		else if(customerType==CustomerManage.INTENTION_CUSTOMER) {
			customAllotDao.resetIntetionAllotLabel(empno);
		}
		
		else if(customerType==CustomerManage.SERVICE_CUSTOMER) {
			customAllotDao.resetServiceAllotLabel(empno);
		}
		
		else if(customerType==CustomerManage.NOT_REGISTER_NEW_CUSTOMER) {
			customAllotDao.resetNotRegAllotLabel(empno);
		}
		
		else if(customerType==CustomerManage.OPEN_SEA_CUSTOMER) {
			customAllotDao.resetTwiceAllotLabel(empno);
		}
	}
	
	/**
	 * 标记电销销售分配标签
	 */
	@Override
	public void resetSpecialEmpAllotLabel(String empno) throws SQLException {
		customAllotDao.resetSpecialEmpAllotLabel(empno);
	}

	@Override
	public CustomAllotConfig getPollInterval() throws SQLException {
		CustomAllotConfig cac = customAllotDao.getPollInterval();
		return cac;
	}

	@Override
	public void updatePollInterval(Integer pollInterval) throws SQLException {

		customAllotDao.updatePollInterval(pollInterval);
	}

}
